package news.paper.tintuc.tinnong.docbao.doctin.GCM;

import java.util.Random;

import news.paper.tintuc.tinnong.docbao.doctin.Activity_Splash;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import news.paper.tintuc.tinnong.docbao.doctin.R;
import news.paper.tintuc.tinnong.docbao.doctin.util.Constrant;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;

public class NotificationController {
	private Context mcontext;
	private String JsonData;

	public NotificationController(Context context, String jsondata) {
		this.mcontext = context;
		this.JsonData = jsondata;
	}

	public void execute() {
		generateNotification(mcontext);
	}

	public void generateNotification(Context context) {
		try {
			NotificationCompat.Builder builder = new NotificationCompat.Builder(
					context);
			builder.setAutoCancel(true);
			JSONObject json;
			json = new JSONObject(JsonData);
			String title = json.getString("Title");
			String message = json.getString("Content");
			String url = json.getString("Link");
			int Type = json.getInt("Type");

			builder.setContentTitle(title);
			builder.setContentText(message);
			builder.setSmallIcon(R.drawable.but_new);
			builder.setDefaults(Notification.DEFAULT_ALL);
			builder.setWhen(System.currentTimeMillis());
			Intent resultIntent = null;
			if (Type == 0) {
			} else if (Type == 1) {
				resultIntent = new Intent(context, Activity_Splash.class);
				showNotify(resultIntent, context, builder);
			} else if (Type == 2) {
				String Packagename = json.getString("Packagename");
				int IsShowInstalled = json.getInt("IsShowInstalled");
				resultIntent = new Intent(Intent.ACTION_VIEW);
				resultIntent.setData(Uri.parse(url));
				if (IsShowInstalled == 1) {
					showNotify(resultIntent, context, builder);
				} else {
					boolean check = Constrant.isAppInstalled(context,
							Packagename);
					if (!check) {
						showNotify(resultIntent, context, builder);
					}
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void showNotify(Intent resultIntent, Context context,
			NotificationCompat.Builder builder) {
		resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
				0, resultIntent, 0);
		builder.setContentIntent(resultPendingIntent);
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		notificationManager.notify(new Random().nextInt(100), builder.build());
	}

}
